package com.renwei.yunlong.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseRefreshFragment;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.event.ChartPasgeRefreseEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by wangqi on 2017/9/29.
 * 解决率
 */

public class WorkResolutionFragment extends BaseRefreshFragment implements OnChartValueSelectedListener, HttpTaskListener, RadioGroup.OnCheckedChangeListener {

    @Bind(R.id.rb_all)
    RadioButton rbAll;
    @Bind(R.id.rb_mouth)
    RadioButton rbMouth;
    @Bind(R.id.rb_week)
    RadioButton rbWeek;
    @Bind(R.id.rb_day)
    RadioButton rbDay;
    @Bind(R.id.rg)
    RadioGroup rg;
    @Bind(R.id.chart1)
    PieChart mChart;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.tv_solve_count)
    TextView tvSolveCount;
    @Bind(R.id.tv_dealing_count)
    TextView tvDealingCount;
    @Bind(R.id.tv_sure_count)
    TextView tvSureCount;
    @Bind(R.id.tv_receiver_count)
    TextView tvReceiverCount;
    private String companyCode; // 筛选公司code
    private String contractId; // 项目id
    private String detailId;
    private String endDates;
    private String startDates;
    private int type;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.fragment_work_resolution;
    }

    @Override
    public void onPageCheck() {
        if (type==0){
            rbAll.toggle();
        }else{
            initData();
        }
    }

    @Override
    protected void initView() {
        initCakeView();

        rg.setVisibility(View.VISIBLE);
        rg.setOnCheckedChangeListener(this);
    }


    /**
     * 筛选
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onScreen(ChartPasgeRefreseEvent event) {
        companyCode = event.getTargetCompanyCode();
        contractId = event.getTargetProjecyCode();
        detailId = event.getTargetServiceCode();

        initData();
    }

    /**
     * 初始化 饼状图
     */
    private void initCakeView() {
        mChart.setUsePercentValues(true);
        mChart.getDescription().setEnabled(false);
        mChart.setExtraOffsets(5, 10, 5, 5);

        mChart.setDragDecelerationFrictionCoef(0.95f);

        mChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(Color.WHITE);

        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(58f);
        mChart.setTransparentCircleRadius(61f);

        mChart.setDrawCenterText(true);

        mChart.setRotationAngle(-90);
        //设置 旋转
        mChart.setRotationEnabled(false);
        mChart.setHighlightPerTapEnabled(true);

        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);
        mChart.setDrawEntryLabels(true);
        // add a selection listener
        mChart.setOnChartValueSelectedListener(this);

        mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // mChart.spin(2000, 0, 360);

        // 设置右上角 显示
        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);

    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", companyCode);
        } else if ("2".equals(companyType)) {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("ownerCode", companyCode);
            map.put("contractId", contractId);
        }
        map.put("dateFlag", type + "");
        map.put("startDates", startDates);
        map.put("endDates", endDates);
        map.put("detailId", detailId);
        ServiceRequestManager.getManager().getWorkSolution(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    private void setChartData(String str1, String str2, String str3, String str4) {

        tvReceiverCount.setText(str1);
        tvDealingCount.setText(str2);
        tvSureCount.setText(str3);
        tvSolveCount.setText(str4);

        int i1 = Integer.parseInt(str1);
        int i2 = Integer.parseInt(str2);
        int i3 = Integer.parseInt(str3);
        int i4 = Integer.parseInt(str4);

        mChart.setCenterText(generateCenterSpannableText(i1 + i2 + i3 + i4));
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        entries.add(new PieEntry(i1, ""));
        entries.add(new PieEntry(i2, ""));
        entries.add(new PieEntry(i3, ""));
        entries.add(new PieEntry(i4, ""));

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        colors.add(getContext().getResources().getColor(R.color.color_work_red));
        colors.add(getContext().getResources().getColor(R.color.color_work_yellow));
        colors.add(getContext().getResources().getColor(R.color.color_work_bule));
        colors.add(getContext().getResources().getColor(R.color.color_work_green));
        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(13f);
        data.setValueTextColor(Color.WHITE);
        mChart.setData(data);

        // undo all highlights
        mChart.highlightValues(null);

        mChart.invalidate();
    }

    private CharSequence generateCenterSpannableText(int maxCount) {
        int length = String.valueOf(maxCount).length();

        SpannableString s = new SpannableString(maxCount + "\n接受工单");
        s.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        s.setSpan(new StyleSpan(Typeface.BOLD), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗体
        s.setSpan(new RelativeSizeSpan(3.0f), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        s.setSpan(new ForegroundColorSpan(Color.parseColor("#999999")), length, length + 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 3,7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗体
//        s.setSpan(new RelativeSizeSpan(3.0f), 3,7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return s;
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.rb_all:
                type= 1;
                break;
            case R.id.rb_mouth:
                type= 2;
                break;
            case R.id.rb_week:
                type= 3;
                break;
            case R.id.rb_day:
                type= 4;
                break;
        }
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                CommonBean bean = new Gson().fromJson(result, CommonBean.class);
                int code = bean.getMessage().getCode();
                if (code == 200) {
                    String[] strs = bean.getRows().split(",");

                    tvTime.setText(strs[0]);
                    setChartData(strs[1], strs[2], strs[3], strs[4]);
                } else {
                    setChartData("0", "0", "0", "0");
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        setChartData("0", "0", "0", "0");
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

}
